import router from '@/router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import { getToken, getRole } from '@/utils/auth'
import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from './store/modules/permission'

NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login', '/'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)

  // 判断是否登录
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const userStore = useUserStore()
      const permissionStore = usePermissionStore()
      //  判断是否有权限
      const hasRoles = userStore.user.roles && userStore.user.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // 如果没有权限，默认给admin
          const roles = [getRole()]
          const _roles = await userStore.changeRoles(roles)
          // 重置路由
          const accessedRoutes = await permissionStore.generateRoutes(_roles)
          accessedRoutes.forEach((route) => {
            router.addRoute(route)
          })
          next({ ...to, replace: true })
        } catch (error) {
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 滚动到顶部
  window.scrollTo(0, 0)
  // finish progress bar
  NProgress.done()
})
